// pages/orderDetails/orderDetails.js
const app = getApp()
var api = require('../../../utils/api.js')
var util = require('../../../utils/util.js');
const wxUploadFile = util.promisify(wx.uploadFile)
Page({

  /**
   * 页面的初始数据
   */
  data: {
    item:{},
   images:[], //支付凭证
   remarkCol:true, //查看支付账号弹窗控制
   cName: app.globalData.companyName,//公司名称
   taxNumber: app.globalData.taxNumber,//税号
   bankName: app.globalData.bankName,//开户行
   bankNumber: app.globalData.bankNumber,//账户
   remarkText:'', //备注
   voucherImg:[] //上传示例图
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var oid = options.oid
     this.setData({
        oid: oid
     })
     
    if(options.linktype){
       this.setData({
          linktype: options.linktype
       })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
     this.orderDetails();
     this.data.voucherImg.push(app.globalData.base_url + 'images/voucher.jpg');
  },
  orderDetails:function(){
    var that = this;
    var oid = this.data.oid;
    api.POST({
      params: { "oid": oid},
      url: app.globalData.base_url + 'couponsorder/info',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          var productList = res.data.data.productList;
          var productDetails = res.data.data;
           if (productDetails.pay_order_img){
              that.setData({
                 images: productDetails.pay_order_img
              })
           }

           if (productDetails.redeem_code) {
              that.setData({
                 redeem_code: productDetails.redeem_code
              })
           }

          that.setData({
            productList: productList,
            productDetails: productDetails
          })
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },
  //确认收货
  receiveOrder: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否确认收货',
      success: function (res) {
        if (res.confirm) {
          api.POST({
            params: { oid: that.data.oid },
            url: app.globalData.base_url + 'order/receipt',
            success: function (res) {
              if (util.isEmpty(res.data.code)) {
                that.onShow();
              } else {
                util.showError(res.data.message);
              }
            },
            fail: function (fail) {
              util.showError("请检查网络");
            }
          })
        }
      }
    })
  },
  //删除订单
  deleteOrder: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否确认删除',
      success: function (res) {
        if (res.confirm) {
          api.POST({
            params: { oid: that.data.oid, type: that.data.productDetails.type},
            url: app.globalData.base_url + 'couponsorder/del',
            success: function (res) {
              if (util.isEmpty(res.data.code)) {
                wx.navigateBack({
                  delta: 1,
                })
              } else {
                util.showError(res.data.message);
              }
            },
            fail: function (fail) {
              util.showError("请检查网络");
            }
          })
        }
      }
    })
  },
  //联系客服
  cllphone: function (e) {
    var phone = e.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  refund:function(e){
    var id = e.currentTarget.dataset.sku_code;
    var status = e.currentTarget.dataset.status;
    var oid = this.data.oid;
    if(status==0){
      wx.redirectTo({
         url: '/center/pages/refundSel/refundSel?oid=' + oid + "&op_id=" + id
      })
    }else if(status == 1){
      wx.redirectTo({
        url: '/center/pages/refundSecond/refundSecond?id=' + id
      })
    } else if (status == 4) {
       wx.redirectTo({
          url: '/center/pages/refundCheck/refundCheck?id=' + id
       })
    }
    else{
      wx.navigateTo({
        url: '/center/pages/refundSuccessful/refundSuccessful?id=' + id
      })
    }
  },
  // 订单支付
  orderPay: function (e) {
    var that = this;
    var oid = this.data.oid;
    wx.showModal({
      title: '提示',
      content: '是否确认支付',
      success: function (res) {
        if (res.confirm) {

          that.wxPayOrder(oid);
        }
      }
    })
  },

  // 订单支付
  //支付接口
  wxPayOrder: function (oid) {
    var params = new Object()
    var that = this;
    params.oid = oid;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'payment/getWechatInfo',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {


          var preData = res.data.data.payinfo;
          wx.requestPayment({
            timeStamp: preData.timeStamp,
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function (res) {
              that.onShow();
            },
            fail: function (error) {
              util.showError("支付失败");
            }
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("网络错误，请检查网络");
      }
    })
  },
  //取消取货
  cancelPickUp: function (e) {
    var params = new Object()
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否取消取货',
      success: function (res) {
        if (res.confirm) {
          api.POST({
            params: { oid: that.data.oid },
            url: app.globalData.base_url + 'order/cancelPick',
            success: function (res) {
              if (util.isEmpty(res.data.code)) {
                that.onShow();
              } else {
                util.showError(res.data.message);
              }
            },
            fail: function (fail) {
              util.showError("请检查网络");
            }
          })
        }
      }
    })
  },

   //取消支付
   cancelPayOrder: function (e) {
      var params = new Object()
      var that = this;
      wx.showModal({
         title: '提示',
         content: '是否取消订单',
         success: function (res) {
            if (res.confirm) {
               api.POST({
                  params: { oid: that.data.oid },
                  url: app.globalData.base_url + 'order/cancelPick',
                  success: function (res) {
                     if (util.isEmpty(res.data.code)) {
                        // that.onShow();
                        wx.navigateBack({
                           delta: 1
                        })
                     } else {
                        util.showError(res.data.message);
                     }
                  },
                  fail: function (fail) {
                     util.showError("请检查网络");
                  }
               })
            }
         }
      })
   },

  //打开柜门
  openDoor: function (e) {
    var that = this;
    var oid =this.data.oid;
    wx.showModal({
      title: '提示',
      content: '是否打开柜门取货?',
      success: function (res) {
        if (res.confirm) {
          api.POST({
            params: { oid: oid },
            url: app.globalData.base_url + 'order/pickup',
            success: function (res) {
              if (util.isEmpty(res.data.code)) {
                util.showError("柜门已打开");
                that.onShow();
              } else {
                util.showError(res.data.message);
              }
            },
            fail: function (fail) {
              util.showError("请检查网络");
            }
          })
        }
      }
    })
  },

  //开发票
  getInvoice: function (e) {
    var that = this;
    var oid = this.data.oid;
    wx.navigateTo({
      url: '/center/pages/invoice/invoice?oid=' + oid
    })
  },
  //预览图片
  //预览图片
  previewImage: function (e) {
    var current = e.target.dataset.src;
    var urls=[]
    urls.push(current)
    wx.previewImage({
      current: current,
      urls: urls
    })
  },
   logisticsLink:util.debounce(function(){
      var oid = this.data.oid;
      wx.navigateTo({
         url: '/center/pages/logistics/logistics?oid=' + oid
      })
   }),
   /**
    * 选择图片
    */
   selectImg: util.debounce(function(e){
      const that = this;
      wx.chooseImage({
         count: 5,
         sourceType: ['album', 'camera'],
         success(res) {
            let images = that.data.images.concat(res.tempFilePaths)
            images = images.length <= 5 ? images : images.slice(0, 5);
            that.setData({
               images: images
            })
         }
      })
   }),

   /**
    * 上传图片
    */
   uploadingImg:util.debounce(function(e){
      const that = this;
      const arr = [];
      const imageBox = this.data.images;
      const oid = this.data.oid;
      const text = this.data.remarkText;
      
      for (let path of imageBox) {
         arr.push(wxUploadFile({
            url: app.globalData.base_url + 'img/saveImage',
            filePath: path,
            name: 'file'
         }))
      }

      wx.showLoading({
         title: '正在上传...',
         mask: true
      })

      Promise.all(arr).then( res => {
         return res.map( item => {
            return JSON.parse(item.data).data.url
         })
      }).catch(err => {
         util.showError(err);
      }).then(urls => {
         urls=JSON.stringify(urls);
         // console.log(urls);
         // return false
         api.POST({
            params: { oid: oid, pay_order_img: urls, pay_order_msg: text},
            url: app.globalData.base_url + 'order/putPayOrder',
            success: function (res) {
               wx.hideLoading();
               if (util.isEmpty(res.data.code)) {
                  util.showError('上传成功!');
                  that.onShow();
               } else {
                  util.showError(res.data.message);
               }
            },
            fail: function (fail) {
               util.showError("请检查网络");
            }
         })
      })

   }),
   /**
    * 提交支付凭证
    */
   submitImg: util.debounce(function(){
      const that = this;
      const imageBox = this.data.images;
      if (imageBox.length < 1) {
         util.showError("请选择需要上传的图片");
         return false
      }
      wx.showModal({
         title: '提示',
         content: '请确认上传信息无误后，再提交（因上传后无法修改）',
         success: function (res) {
            if (res.confirm) {
               that.uploadingImg();
            }
         }
      })
   }),
   /**
    * 删除图片
    */
   deleteImg:util.debounce(function(e){
      const that = this;
      const index = e.currentTarget.dataset.index;
      let imgBox = that.data.images;
      imgBox.splice(index, 1);
      that.setData({
         images: imgBox
      })
   }),

   /**
    * 图片预览
    */
   handleImagePreview(e) {
      const idx = e.target.dataset.index
      const images = this.data.images
      wx.previewImage({
         current: images[idx],  //当前预览的图片
         urls: images,  //所有要预览的图片
      })
   },

   remarkCancel: function () {
      this.setData({
         remarkCol: true
      })
   },

   remarkOpen: function () {
      this.setData({
         remarkCol: false
      })
   },
/**
 * 复制
 */
   copyRedeemCode: util.debounce(function(){
      var code = this.data.redeem_code
      wx.setClipboardData({
         data: code,
         success(res) {
            util.showError("复制成功");
         }
      })
   }),
   remarkInput: util.debounce(function (e) {
      var text = e.detail.value
      this.setData({
         remarkText: text
      })
   }),

   goLink: function () {
      wx.switchTab({
         url: '/pages/index/index'
      });
   },

   voucherImgCol:function(){
      console.log(this.data.voucherImg[0])
      wx.previewImage({
         current: this.data.voucherImg[0],  //当前预览的图片
         urls: this.data.voucherImg,
      })
   }

})